package com.qf.conf;

import com.alibaba.fastjson.JSON;
import com.qf.consts.Code;
import com.qf.pojo.R;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FailLoginHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        R r = null;
        if (exception instanceof InternalAuthenticationServiceException){
            //用户名错误
            r = R.error("用户名错误").putCode(Code.USERNAME_ERROR);
        }else{
            //密码错误
            r = R.error("密码错误").putCode(Code.PASSWORD_ERROR);
        }

        String json = JSON.toJSONString(r);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
